package com.alianzamedica.controllers.module;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.objectsearch.web.tools.Converter;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Module;
import com.alianzamedica.controllers.constants.ActionConstants;
import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
public class ModuleListAction extends Action {

	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		search.setDefaultDialect(ObjectSearch.MYSQL_DIALECT);
		search.setLike(true);
		Integer pageNum = Converter.string2Integer(request
				.getParameter("pageNum"));
		if (pageNum == null) {
			pageNum = 1;
		}
		String name = request.getParameter("name");
		String url = request.getParameter("url");
		Module module = new Module();
		if (name != null && name.trim().length() > 0) {
			module.setName(name);
		}
		if (url != null && url.trim().length() > 0) {
			module.setUrl(url);
		}
		Integer totalPages = search.getTotalPages(module, ActionConstants.PAGE_SIZE);
		ArrayList list = search.getPagedQuery(module, null, pageNum, ActionConstants.PAGE_SIZE);
		request.setAttribute("totalPages", totalPages);
		request.setAttribute("modules", list);

		return mapping.findForward("success");
	}

}
